package com.ta.gulimall.product.controller.redisson;

import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RedWriteLockController {
    @Autowired
    RedissonClient redissonClient;

    /**
     * 读写锁：读锁
     * @return
     */
    @GetMapping("/redLock")
    public String redLock() {
        RReadWriteLock redWriteLock = redissonClient.getReadWriteLock("redWriteLock");
        RLock rLock = redWriteLock.readLock();
        rLock.lock();
        System.out.println("==============读锁"+ Thread.currentThread().getId() + "在加锁");
        try{
            Thread.sleep(3000);
        }catch (Exception e){
            throw new RuntimeException("", e);
        }finally {
            rLock.unlock();
            System.out.println("==============读锁"+ Thread.currentThread().getId() + "在解锁");
        }

        return "redLock";
    }

    /**
     * 读写锁：写锁
     * @return
     */
    @GetMapping("/writLock")
    public String writLock() {
        RReadWriteLock redWriteLock = redissonClient.getReadWriteLock("redWriteLock");
        RLock rLock = redWriteLock.writeLock();
        rLock.lock();
        try{
            System.out.println("==============写锁"+ Thread.currentThread().getId() + "在加锁");
            Thread.sleep(5000);
        }catch (Exception e){
            throw new RuntimeException("", e);
        }finally {
            rLock.unlock();
            System.out.println("==============写锁"+ Thread.currentThread().getId() + "在解锁");
        }

        return "writLock";
    }

}
